//
//  YZAutoFormVC.m
//  VET
//
//  Created by Lam BG on 2018/7/13.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAutoFormVC.h"
#import "YZPopupController.h"

#import "YZAutoVCModel.h"
#import "YZAutoRowModel.h"
#import "YZAutoItemModel.h"
#import "YZAutoSectionModel.h"

#import "YZPopupCustomView.h"
#import "YZBaseAutoCell.h"

// api
#import "YZWorkbenchAPI.h"

// other
#import "YZAutoFormHeader.h"
#import "YZJsonFileLoader.h"
#import "YZAutoCellFactory.h"

#import "MJExtension.h"

// category
#import "UIView+Frame.h"
#import "NSArray+YZCategory.h"
#import "UIResponder+Router.h"


@interface YZAutoFormVC ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation YZAutoFormVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (self.avcModel.vcType != AutoVCTypeNewDailWrok) self.tableView.backgroundColor = kColorWithHex(0xE9EAEB);
    
    // 注册 cells
    [[YZAutoCellFactory sharedInstance] registerAutoFormCells:self.tableView];
    
    self.navigationItem.leftBarButtonItem  = [self barButtonItemWithTitle:@"取消" titleColor:kColorWithHex(0x393939) target:self action:@selector(leftClicked)];
    
    // 猪只免疫详情 猪群免疫详情 猪只治疗详情
    AutoVCType vcType = self.avcModel.vcType;
    if (self.params[@"id"] &&
        (vcType == AutoVCTypeImmuneSwinery ||
         vcType == AutoVCTypeImmuneSwine ||
         vcType == AutoVCTypeTreatSwine)) {
        
        self.navigationItem.rightBarButtonItem = [self barButtonItemWithTitle:@"删除" titleColor:kColorWithHex(0x32BE60) target:self action:@selector(deleteClicked)];
        
        if (vcType == AutoVCTypeTreatSwine) self.title = @"治疗详情";
        if ((vcType == AutoVCTypeImmuneSwinery || vcType == AutoVCTypeImmuneSwine)) self.title = @"免疫详情";
            
    } else if (vcType == AutoVCTypeSwineryTransferIn ||
               vcType == AutoVCTypeSwineryTransferOut ||
               vcType == AutoVCTypeSwineryDeadSwine) {
        
        // 不添加 右上按钮
    } else {
        
        self.navigationItem.rightBarButtonItem = [self barButtonItemWithTitle:@"保存" titleColor:kColorWithHex(0x32BE60) target:self action:@selector(saveClicked)];
    }
    
    
    // 键盘通知监听
    // 注册键盘出现的通知
    @weakify(self)
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        
        @strongify(self)
        [self keyboardWillShow:x];
    }];
    
    // 注册键盘消失的通知
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillHideNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        
        @strongify(self)
        [self keyboardWillHide:x];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

#pragma mark - 数据获取

- (void)loadDataFromNetwork {
    
    AutoVCType vcType = self.avcModel.vcType;
    // 猪群
    if (vcType == AutoVCTypeCardNewSwinery) {
        
        NSString *swineHerdId = self.params[@"id"];
        // 编辑 猪群
        [[YZWorkbenchAPI getSwineryInfoAPI:swineHerdId] subscribeNext:^(NSDictionary *params) {
            
            self.params = params;
            [self loadDataFromMermory];
            [self.tableView reloadData];
            
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪只
    if (vcType == AutoVCTypeCardNewSwine) {
        
        NSString *swineHerdId = self.params[@"id"];
        // 编辑 猪只
        [[YZWorkbenchAPI getSwineInfoAPI:swineHerdId] subscribeNext:^(NSDictionary *params) {
            
            self.params = params;
            [self loadDataFromMermory];
            [self.tableView reloadData];
            
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 获取猪群免疫详情
    if (vcType == AutoVCTypeImmuneSwinery) {
        
        NSString *swineHerdId = self.params[@"id"];
        // 编辑 猪只
        [[YZWorkbenchAPI vaccinationImmuneSwineryAPIWithParams:swineHerdId] subscribeNext:^(NSDictionary *params) {
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:params];
            [dict setObject:self.params[@"objectIds"] forKey:@"objectIds"];
            self.params = dict;
            self.isUnEdit = YES;
            [self loadDataFromMermory];
            [self.tableView reloadData];
            
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 获取猪只免疫详情
    if (vcType == AutoVCTypeImmuneSwine) {
        
        NSString *swineHerdId = self.params[@"id"];
        // 编辑 猪只
        [[YZWorkbenchAPI vaccinationImmuneSwineAPIWithParams:swineHerdId] subscribeNext:^(NSDictionary *params) {
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:params];
            [dict setObject:self.params[@"objectIds"] forKey:@"objectIds"];
            self.params = dict;
            self.isUnEdit = YES;
            [self loadDataFromMermory];
            [self.tableView reloadData];
            
        } error:^(NSError * _Nullable error) {
            
        }];
    }
}

- (void)loadDataFromMermory {
    
    // 寻找匹配的 item
    [self.data enumerateObjectsUsingBlock:^(YZAutoSectionModel *section, NSUInteger idx, BOOL * _Nonnull stop) {
        [section.formRows enumerateObjectsUsingBlock:^(YZAutoRowModel *row, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSString *paramKey = row.paramKey;
            id obj = self.params[paramKey];
            obj = kNullable(obj);
            if (obj) {
                // 判断 obj 类型
                if ([obj isKindOfClass:[NSString class]]) {
                    
                    // string 直接赋值
                    row.paramValue = obj;
                    row.displayValue = obj;
                    
                } else if ([obj isKindOfClass:[NSDictionary class]]) {
                    
                    YZAutoItemModel *item = [YZAutoItemModel mj_objectWithKeyValues:obj];
                    row.paramValue = [@(item.itemKey) stringValue];
                    row.displayValue = item.itemValue;
                    
                } else if ([obj isKindOfClass:[NSArray class]]) {
                
                    //TODO:: 症状表现
                    if ([@"symptonList" isEqualToString:paramKey]) {
                        
                        if (((NSArray*)obj).count) {
                            
                            obj = obj[0];
                            row.paramValue = obj[@"id"];
                            row.displayValue = obj[@"sympton"];
                        }
                    }
                    
                } else if ([obj isKindOfClass:[YZAutoItemModel class]]) {
                    
                    YZAutoItemModel *item = (YZAutoItemModel*)obj;
                    row.paramValue = [@(item.itemKey) stringValue];
                    row.displayValue = item.itemValue;
                    
                } else {
                    
                    // 默认为整型
                    row.paramValue   = [@([obj doubleValue]) stringValue];
                    row.displayValue = [@([obj doubleValue]) stringValue];
                }
            }
        }];
    }];
    
    // 特殊参数处理
    [self specialParmas];
}

- (void)specialParmas {
    
    if (self.avcModel.vcType == AutoVCTypeCardNewSwine) {
        // 寻找匹配的 item
        [self.data enumerateObjectsUsingBlock:^(YZAutoSectionModel *section, NSUInteger idx, BOOL * _Nonnull stop) {
            [section.formRows enumerateObjectsUsingBlock:^(YZAutoRowModel *row, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if ([@"swineSex" isEqualToString:row.paramKey]) {
                    
                    // 母猪/公猪 选中
                    if ([row.paramValue integerValue] == 4 || [row.paramValue integerValue] == 3) {
                        
                        // 显示胎龄
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:0];
                        YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
                        // NO 为可用 NO 为不可用
                        rowModel.isUnable = [row.paramValue integerValue] == 3;
                    }
                }
            }];
        }];
    }
    
    if (self.avcModel.vcType == AutoVCTypeCardDeadSignSwinery) {
        
        // 猪群死淘登记 设置数量最大值
        if ([self.params.allKeys containsObject:@"realQty"]) {
            
            NSInteger realQty = [self.params[@"realQty"] integerValue];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
            YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
            // 设置最大值
            rowModel.maxValue = realQty;
        }
    }
}

#pragma mark - 子类实现

- (void)loadData {
    [super loadData];
    
    if (self.params.count && [kURI isEqualToString:self.params[kURI]]) {
        
        // 从服务器获取数据
        [self loadDataFromNetwork];
        
    } else if (self.params.count) {
        
        // 如果有参数带过来赋值
        [self loadDataFromMermory];
    }
}

- (NSArray *)viewJson:(NSString *)fileName {
    
    NSDictionary *data = [YZJsonFileLoader loadLocalJsonWithFileName:fileName];
    NSArray *jsonArray = data[@"sections"];
    
    return jsonArray;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
    AutoVCType vcType = self.avcModel.vcType;
    // 新建每日待办 tips
    if (vcType == AutoVCTypeNewDailWrok) {
        if ([@"taskAlarm" isEqualToString:rowModel.paramKey]) {
            return 56;
        }
    }
    
    // 新增免疫 tips
    if (vcType == AutoVCTypeImmuneSwinery || vcType == AutoVCTypeImmuneSwine) {
        if ([@"vaccineDosage" isEqualToString:rowModel.paramKey]) {
            return 68;
        }
    }
    
    if (rowModel.isUnable) return 0;
    
    return UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
    cell.hidden = rowModel.isUnable;
}

// rows in section nums
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    YZAutoSectionModel *sectionModel = self.data[section];
    NSArray *rows = sectionModel.formRows;
    
    return rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 根据 row 类型生成 cell
    YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
    rowModel.indexPath = indexPath;
    
    YZBaseAutoCell *cell = (YZBaseAutoCell*)[[YZAutoCellFactory sharedInstance] generateCell:tableView withRowModel:rowModel];
    if (self.isUnEdit) rowModel.isUnEdit = self.isUnEdit;
    cell.rowModel = rowModel;
    
    return cell;
}



#pragma mark - event action

- (void)routeEvent:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    
    if (self.avcModel.vcType == AutoVCTypeCardNewSwine) {
        
        if (userInfo && userInfo[@"item"]) {
            
            YZAutoItemModel *item = (YZAutoItemModel*)userInfo[@"item"];
            // 母猪/公猪 选中
            if (item.itemKey == 4 || item.itemKey == 3) {
                
                // 显示胎龄
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:0];
                YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
                // NO 为可用 NO 为不可用
                rowModel.isUnable = item.itemKey == 3;
                [self.tableView reloadData];
            }
        }
    }
    
    if (self.avcModel.vcType == AutoVCTypeMutableSwinery) {
        
        if (userInfo && userInfo[@"result"]) {
            
            // 比对是否更换猪群
            NSString *result = userInfo[@"result"];
            NSIndexPath *groupPath = [NSIndexPath indexPathForRow:0 inSection:0];
            YZAutoRowModel *groupModel = (YZAutoRowModel*)[self.data formRowInSection:groupPath];
            if ([result isEqualToString:groupModel.paramValue]) {
                
                return;
            }
            

            NSInteger realQty = [userInfo[@"realQty"] integerValue];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
            YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
            // 设置最大值
            rowModel.maxValue = realQty;
            rowModel.displayValue = @"";
            rowModel.paramValue = @"";
            [self.tableView reloadData];
        }
    }
    
    if (self.avcModel.vcType == AutoVCTypeCardTransferSwinery) {
        
        if (userInfo && userInfo[@"item"]) {
            
            YZAutoItemModel *item = (YZAutoItemModel*)userInfo[@"item"];
            // 获取 业务类型 row
            NSIndexPath *typePath = [NSIndexPath indexPathForRow:2 inSection:0];
            YZAutoRowModel *rowTypeModel = (YZAutoRowModel*)[self.data formRowInSection:typePath];
            if ([rowTypeModel.paramValue integerValue] == item.itemKey) {
                
                return;
            }
            
            
            // 状态变动时
            NSInteger realQty = 0;
            // 转入
            if (item.itemKey == 61) realQty = 999999;
            // 转出
            if (item.itemKey == 62) realQty = [self.params[@"realQty"] integerValue];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
            YZAutoRowModel *rowModel = (YZAutoRowModel*)[self.data formRowInSection:indexPath];
            // 设置最大值
            rowModel.maxValue = realQty;
            rowModel.displayValue = @"";
            rowModel.paramValue = @"";
            [self.tableView reloadData];
        }
    }
}

- (void)leftClicked {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveClicked {
    
    // 根据不同类型不同 api 调用
    NSMutableDictionary *params = [self.data yz_autoParams];
    AutoVCType vcType = self.avcModel.vcType;
    
    if (params == nil) {
        
        [SVProgressHUD yz_showMessage:@"请将必填项输入完整"];
        return;
    }
    
    // 每日待办
    if (vcType == AutoVCTypeNewDailWrok) {
        
        if (![params.allKeys containsObject:@"taskDetail"]) {
            
            [SVProgressHUD yz_showMessage:@"请输入任务内容"];
            return;
        }
        
        if (![params.allKeys containsObject:@"taskAlarm"]) {
            
            [SVProgressHUD yz_showMessage:@"请选择提醒"];
            return;
        }
        
        if (self.params[@"id"]) {
            
            // 更新每日待办
            [[YZWorkbenchAPI updateDailyWorkAPI:self.params[@"id"] params:params] subscribeNext:^(id  _Nullable x) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kUndoRefreshNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            } error:^(NSError * _Nullable error) {
                
            }];
            
        } else {
         
            // 新建每日待办
            [[YZWorkbenchAPI newDailyWorkAPI:params] subscribeNext:^(id  _Nullable x) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kUndoRefreshNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            } error:^(NSError * _Nullable error) {
                
            }];
        }
    }
    
    // 猪群
    if (vcType == AutoVCTypeCardNewSwinery) {
        
        if (self.params[@"id"]) {
            
            // 更新 猪群
            [[YZWorkbenchAPI updateSwineryAPI:self.params[@"id"] params:params] subscribeNext:^(id  _Nullable x) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            } error:^(NSError * _Nullable error) {
                
            }];
            
        } else {
            
            // 新建 猪群
            [[YZWorkbenchAPI newSwineryAPI:params] subscribeNext:^(id  _Nullable x) {
                
                
                YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                @weakify(self)
                [customView setupUIWithTitle:nil message:@"建档成功!" confirmTitle:@"继续建档" cancelTitle:@"关闭" confirmHandler:^{
                    
                    @strongify(self)
                    self.params = nil;
                    [self loadData];
                    [self.tableView reloadData];
                    [self.YZ_popupController dismiss];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
                    
                } cancelHandler:^{
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self.YZ_popupController presentContentView:customView];
     
            } error:^(NSError * _Nullable error) {
                
            }];
        }
    }
    
    // 结批
    if (vcType == AutoVCTypeCardFinishSwinery) {
        
        // 结批
        [[YZWorkbenchAPI FinishedSwineryAPI:self.params[@"id"] params:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 转入转出
    if (vcType == AutoVCTypeCardTransferSwinery) {
        
        // 转入转出
        [[YZWorkbenchAPI transferSwineryAPI:self.params[@"id"] params:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪群 死淘登记
    if (vcType == AutoVCTypeCardDeadSignSwinery) {
        
        // 猪群 死淘登记 （objectType 猪只：swine、猪群：herd）
        NSString *dieoutStatus = @"";
        if ([self.params.allKeys containsObject:@"herdState"]) {
            
            // 猪群死前状态
            dieoutStatus = self.params[@"herdState"][@"id"];
        }
        [params setObject:@[@{@"objectId" : self.params[@"id"], @"dieoutStatus" : dieoutStatus, @"objectType" : @"herd"}] forKey:@"dieoutObjectList"];
        [[YZWorkbenchAPI deadSignAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪只
    if (vcType == AutoVCTypeCardNewSwine) {
        
        BOOL newFlag = YES;
        if (self.params[@"id"]) {
            
            // 更新
            newFlag = NO;
            [params setObject:self.params[@"id"] forKey:@"id"];
        }
        // 新建 / 更新 猪只
        [[YZWorkbenchAPI newSwineAPI:params] subscribeNext:^(id  _Nullable x) {
            
            if (newFlag) {
                // 新建
                YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                @weakify(self)
                [customView setupUIWithTitle:nil message:@"建档成功!" confirmTitle:@"继续建档" cancelTitle:@"关闭" confirmHandler:^{
                    
                    @strongify(self)
                    self.params = nil;
                    [self loadData];
                    [self.tableView reloadData];
                    [self.YZ_popupController dismiss];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineRefreshNotification object:nil];
                    
                } cancelHandler:^{
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineRefreshNotification object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self.YZ_popupController presentContentView:customView];
                
            } else {
                
                // 更新
                [[NSNotificationCenter defaultCenter] postNotificationName:kSwineRefreshNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪只 死淘登记
    if (vcType == AutoVCTypeCardDeadSignSwine) {
        
        // 猪群 死淘登记 （objectType 猪只：swine、猪群：herd）
        NSString *dieoutStatus = @"";
        if ([self.params.allKeys containsObject:@"swineState"]) {
            
            // 猪只死前状态
            dieoutStatus = self.params[@"swineState"][@"id"];
        }
        
        [params setObject:@"1" forKey:@"dieoutNum"];
        [params setObject:@[@{@"objectId" : self.params[@"id"], @"dieoutStatus" : dieoutStatus, @"objectType" : @"swine"}] forKey:@"dieoutObjectList"];
        [[YZWorkbenchAPI deadSignAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSwineRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    
    // 猪群 新增免疫
    if (vcType == AutoVCTypeImmuneSwinery) {
        
        [params setObject:@"herd" forKey:@"objectType"];
        [[YZWorkbenchAPI vaccinationAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪只 新增免疫
    if (vcType == AutoVCTypeImmuneSwine) {
        
        [params setObject:@"swine" forKey:@"objectType"];
        [[YZWorkbenchAPI vaccinationAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 猪只 新增治疗
    if (vcType == AutoVCTypeTreatSwine) {
        
        [[YZWorkbenchAPI treatSwineAPI:params] subscribeNext:^(id  _Nullable x) {
            
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 多选猪只 死淘登记
    if (vcType == AutoVCTypeMutableSwine) {
        
        [[YZWorkbenchAPI deadSignAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kDieoutRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
    
    // 多选猪群 死淘登记
    if (vcType == AutoVCTypeMutableSwinery) {
        
        [[YZWorkbenchAPI deadSignAPIWithParams:params] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kDieoutRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }

}

- (void)deleteClicked {
    
    // 猪只免疫 猪群免疫
    AutoVCType vcType = self.avcModel.vcType;
    if (vcType == AutoVCTypeImmuneSwine ||
        vcType == AutoVCTypeImmuneSwinery) {
        
        // 猪只 免疫删除 // 猪群 免疫删除
        NSString *vaccinationObjectId = self.params[@"vaccinationObjectId"];
        [[YZWorkbenchAPI deleteVaccinationAPIWithParams:vaccinationObjectId] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kListRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
        
    } else if (vcType == AutoVCTypeTreatSwine) {
        
        // 删除治疗详情
        NSString *treatmentId = self.params[@"id"];
        [[YZWorkbenchAPI deleteTreatSwineAPI:treatmentId] subscribeNext:^(id  _Nullable x) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kListRefreshNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } error:^(NSError * _Nullable error) {
            
        }];
    }
}

#pragma mark - 键盘监听事件处理方法

// 键盘显示事件
- (void)keyboardWillShow:(NSNotification *)notification {
    
    // 获取获取焦点的 view
    UIView *firstView = [self firstView:self.tableView];
    CGRect frame = [firstView convertRect:firstView.bounds toView:self.tableView];
    if (frame.origin.y >= ((float)kScreenHeight / 2)) {
        
        // 获取键盘高度，在不同设备上，以及中英文下是不同的
        CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        
        // 计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
        CGFloat offset = kbHeight;
        
        // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
        double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        
        // 将视图上移计算好的偏移
        if(offset > 0) {
            [UIView animateWithDuration:duration animations:^{
                self.tableView.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
            }];
        }
    }
}

// 键盘消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (UIView*)firstView:(UIView*)view {
    
    UIView *firstView = nil;
    for (UIView *subView in view.subviews) {
        
        if (subView.isFirstResponder) {
            firstView = subView;
            break;
        } else {
            if (subView.subviews.count) {
                firstView = [self firstView:subView];
                if (firstView) break;
            }
        }
    }
    
    return firstView;
}

@end
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
